// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
const _ = db.command

const user = db.collection('user')

function Message(code = 1, msg = '', data = {}) {
  return {
    code,
    msg,
    data
  };
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.action) {
    case 'setPhone': {
      return setPhone(event)
    }
    case 'loginByOpenid': {
      return loginByOpenid(event)
    }
    case 'getUser': {
      return getUser(event)
    }
    case 'improve': {
      return improve(event)
    }
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}
/**
 * 根据手机号登录 因个人帐号无法获取手机号 无法使用
 */
async function setPhone(event) {
  const {
    OPENID
  } = cloud.getWXContext()
  const {
    errCode,
    list
  } = await cloud.getOpenData({
    list: [event.cloudID]
  })
  if (errCode != 0) {
    return Message(-2, "微信手机号获取失败")
  }

  const {
    phoneNumber
  } = list[0].data;
  //判断手机号是否存在
  let {
    data
  } = await user.where({
    phone: phoneNumber
  }).get();
  //可能存在手动导入的用户 
  if (data.length > 0) {
    const [u] = data;
    //更新记录填入手机号和openid
    await user.doc(u._id).update({
      data: {
        _openid: OPENID,
        wxPhone: phoneNumber,
        "updateTime": db.serverDate(),
      }
    })
    return checkUser(data);
  } else {
    //新增一个用户
    data = await user.add({
      data: {
        "_openid": OPENID,
        "name": "",
        "phone": "",
        "role": 0,
        "workCard": "",
        "groupID": [],
        "createTime": db.serverDate(),
        "updateTime": db.serverDate(),
        "department": "",
        "wxPhone": phoneNumber,
        "status": 1.0
      }
    })
    return Message(-3, "个人资料未填写")
  }
}
/**
 * 登录注册
 */
async function loginByOpenid(event) {
  const {
    OPENID
  } = cloud.getWXContext()
  const result = await getUser();
  if (result.length > 0) {
    return checkUser(result);
  } else {
    await user.add({
      data: {
        "_openid": OPENID,
        "name": "",
        "phone": "",
        "role": 0,
        "workCard": "",
        "groupID": [],
        "createTime": db.serverDate(),
        "updateTime": db.serverDate(),
        "department": "",
        "wxPhone": "",
        "status": 1
      }
    })
    return Message(-3, "个人资料未填写")
  }
}
/**
 * 根据OPENID获取用户信息
 */
async function getUser(event) {
  let {
    OPENID
  } = cloud.getWXContext()
  console.log("OPENID", OPENID)
  OPENID = OPENID || event.openId
  const {
    data
  } = await user.where({
    _openid: OPENID
  }).get();
  return data;
}
/**
 * 检查资料是否填写
 */
function checkUser([u]) {
  if (u.status == 0) {
    return Message(-5, "帐号已经被锁定");
  } else if (!u.name || u.name == "") {
    return Message(-3, "", "个人资料未填写");
  } else {
    code = 1;
    return Message(1, "", {
      role: u.role
    });
  }
}
/**
 * 登录角色校验 
 */
async function improve(event) {
  const {
    name,
    pass,
    department,
    phone
  } = event;
  if(name.length>20 || pass.length>50 || department.length > 20 || phone.length > 11){
    return Message(-5,"参数错误");
  }
  const {
    OPENID
  } = cloud.getWXContext()
  const {
    data: groups
  } = await db.collection('group').get();
  let role = 0;
  let gid = [];
  //根据密码校验是哪个集团的
  groups.map(item => {
    if (item.password === pass) {
      role = 1;
    }
    if (item.driverPassword === pass) {
      role = 2;
    }
    gid.push(item._id)
  })
  if (role == 0) {
    return Message(-4,"密码错误")
  }
  await user.where({
    _openid: OPENID,
  }).update({
    data: {
      updateTime: db.serverDate(),
      role,
      groupID: gid,//公司ID
      name,
      department,
      phone,
    }
  })
  return Message(1)
}